import random
import time
import os
from flask import Flask, jsonify, request, send_file
import requests, json

from WXBizDataCrypt import WXBizDataCrypt
from model import Product
from model import Classify

app = Flask(__name__)


@app.route("/swiper/<id>", methods=['GET'])
def swiperPhoto(id):  # 獲取產品ID在數據庫里找產品的行，再返回地址等信息
    product_list = []
    for i in range(1, 6):
        f = Product.get(product_id=i)
        message = {"url": f.img_url, "id": f.product_id}
        product_list.append(message)
    if request.method == 'GET':
        return {"list": product_list, "meta": {"msg": "获取成功", "status": 200}}


@app.route("/classify/<id>", methods=['GET'])
def classifyPhoto(id):
    type_list = []
    for i in range(1, 5):
        f = Classify.get(id=i)
        message = {"url": f.img_url, "name": f.name}
        type_list.append(message)
    if request.method == 'GET':
        return {"list": type_list, "meta": {"msg": "获取成功", "status": 200}}


@app.route("/productList/<pageSize>/<alreadyGot>", methods=['GET'])
def productList(pageSize, alreadyGot):  # 獲取產品ID在數據庫里找產品的行，再返回地址等信息
    product_dict_list = Product.select().dicts()
    product_list = []
    count = 0
    for i in range(int(alreadyGot) + 6, len(product_dict_list)):
        f = Product.get(product_id=i)
        message = {"product_id": f.product_id, "img_url": f.img_url, "productName": f.productName, "price": f.price,
                   "unit": f.unit}
        product_list.append(message)
        count += 1
        if count >= int(pageSize):
            break
    if request.method == 'GET':
        return {"list": product_list, "meta": {"msg": "获取成功", "status": 200}, "total": len(product_dict_list)}


@app.route("/search/<string:keyWord>", methods=['GET'])
def searchList(keyWord):  # 搜索有此关键字的產品
    product_list = []
    for i in range(6, 156):
        f = Product.get(product_id=i)
        if keyWord in f.productName:
            message = {"url": f.img_url, "name": f.productName, "price": f.price, "unit": f.unit, "id": f.product_id}
            product_list.append(message)
    if request.method == 'GET':
        return {"list": product_list, "meta": {"msg": "获取成功", "status": 200}}


@app.route("/classify/type/<typeName>/<pageSize>/<alreadyGot>")
def typeList(typeName, pageSize, alreadyGot):
    type_dict_list = Product.select().where(Product.type == typeName).dicts()
    product_list = []
    count = 0
    for i in range(int(alreadyGot), len(type_dict_list)):
        f = type_dict_list[i]
        message = {"img_url": f["img_url"], "productName": f["productName"], "price": f["price"], "unit": f["unit"],
                   "product_id": f["product_id"]}
        product_list.append(message)
        count += 1
        if count >= int(pageSize):
            break

    if request.method == 'GET':
        return {"list": product_list, "meta": {"msg": "获取成功", "status": 200}, "total": len(type_dict_list)}


@app.route("/product/detail/<id>")
def getProductDetail(id):
    print(id)
    product_detail = Product.select().where(Product.product_id == int(id)).dicts()
    if request.method == 'GET':
        return {"detail": product_detail[0], "meta": {"msg": "获取成功", "status": 200}}


@app.route("/user/login/<a>", methods=["POST"])
def userLogin(a):
    data = json.loads(request.get_data().decode('utf8'))  # 将前端Json数据转为字典
    appID = 'wx24c79f892a980e90'  # 开发者关于微信小程序的appID
    appSecret = 'd7f455b5ee54804778efc2355d0a60d3'  # 开发者关于微信小程序的appSecret
    code = data['code']  # 前端POST过来的微信临时登录凭证code
    encryptedData = data['encryptedData']
    iv = data['iv']
    req_params = {
        'appid': appID,
        'secret': appSecret,
        'js_code': code,
        'grant_type': 'authorization_code'
    }
    wx_login_api = 'https://api.weixin.qq.com/sns/jscode2session'
    response_data = requests.get(wx_login_api, params=req_params)  # 向API发起GET请求
    resData = response_data.json()
    openid = resData['openid']  # 得到用户关于当前小程序的OpenID
    session_key = resData['session_key']  # 得到用户关于当前小程序的会话密钥session_key

    pc = WXBizDataCrypt(appID, session_key)  # 对用户信息进行解密
    userinfo = pc.decrypt(encryptedData, iv)  # 获得用户信息
    print(userinfo)
    token = openid + session_key + str(time.time) + str(random.randrange(1, 9999999))
    message = {'user_name': str(userinfo['nickName']),
               'user_email_code': 'findUserInDB.user_email_code',
               'user_gender': str(userinfo['gender']),
               'user_qq': 'aaaaaaaa',
               'user_education': 'aaaa',
               'user_hobby': 'findUserInDB.user_hobby',
               'user_introduce': 'findUserInDB.user_introduce',
               'user_is_seller': 'findUserInDB.user_is_seller',
               'token': str(token)}
    if openid and session_key:
        return {"message": message, "meta": {"msg": "获取成功", "status": 200}}
    return {"message": "", "meta": {"msg": "获取失败", "status": 500}}


@app.route("/mine/shop/create/order", methods=["POST"])
def order():
    order_detail = json.loads(request.get_data().decode('utf-8'))
    message = {"order_id": 45, "user_id": 12, "order_number": "GD20200427000000000045", "order_price": 0.1,
               "order_pay": "0", "is_send": "否",
               "trade_no": "", "order_fapiao_title": "个人", "consignee_addr": "南京市开心村", "pay_status": "0",
               "create_time": 23232121, "update_time": 1313414,
               "order_detail": order_detail}
    return {"message": message, "meta": {"msg": "获取成功", "status": 200}}


@app.route("/mine/shop/pay/order", methods=["POST"])
def orderpay():
    order_number = json.loads(request.get_data().decode('utf-8'))

    message = {"pay": {"timeStamp": "1525681145", "nonceStr": "BkPggorBxZwPGXe3",
                       "package": "prepay_id=wx071619042918087bb4c1d3d72999385683",
                       "signType": "MD5", "paySign": "D1642DEEF1663C8012EDEB9297E1D516"}, "order_number": order_number}
    return {"message": message, "meta": {"msg": "获取成功", "status": 200}}


@app.route("/information/inf", methods=["GET"])
def informationList():
    message = {"list": [{"img_url": "/static/farm_shop_mall/informationImage/微信图片_20220624094634.png",
                         "title": "最新9类，34项！2022年重点强农惠农政策发布!", "date": "2022/06/22 12:08"},
                        {"img_url": "/static/farm_shop_mall/informationImage/微信图片_20220624100124.png",
                         "title": "【大国“粮”策】战“三夏” 夺丰收｜又是一季丰收粮！河北今年夏粮丰收已成定局", "date": "2022-06-23 06:05"},
                        {"img_url": "/static/farm_shop_mall/informationImage/微信图片_20220624100240.png",
                         "title": "湖南嘉禾烟草：政策技术多措并举 助力乡村振兴开新局", "date": "2022-06-23 17:39"},
                        {"img_url": "/static/farm_shop_mall/informationImage/微信图片_20220624100505.png",
                         "title": "嵩明管好惠民惠农卡 让“一卡通”直通千家万户", "date": "2022/06/23 14:23"},
                        {"img_url": "/static/farm_shop_mall/informationImage/微信图片_20220624100718.png",
                         "title": "村口正式設立西瓜銷售網點!", "date": "2022/06/21 10:23"}, ]}
    return {"data": message, "meta": {"msg": "succeed", "status": 200}}


@app.route("/")
def index():
    return '欢迎使用微信云托管！'


if __name__ == '__main__':
    #app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 80)))
    app.run()
